import { type RouteRecordName } from 'vue-router'
import { defineStore } from 'pinia'
import { constantRoutes, router } from '@/router'
import {
    getConstantRouteNames,
    OpenType,
    transformMenu,
    transformSearchMenus
} from '@/utils'
import { JBoltApi } from '@/utils/request'
import { PageNames } from '@/router/routes/pagenames'
import type { ResData } from '@/typings/request'
import type { Menu } from '@/typings/menu'
import DemoMenus from '@/constants/demomenu'
import { useAuthStore } from '../auth'

interface RouteState {
    /** 是否初始化了权限路由 */
    isInitAuthRoute: boolean
    /** 路由首页name(前端静态路由时生效，后端动态路由该值会被后端返回的值覆盖) */
    routeHomeName: string
    /** 菜单 */
    menus: App.GlobalMenuOption[]
    /** 搜索的菜单 */
    searchMenus: Menu[]
    /** 缓存的路由名称 */
    cacheRoutes: string[]
    /** 清除缓存的路由名称 ，在刷新页面和关闭页面时用的 */
    clearCacheRoutes: string[]
}

export const useRouteStore = defineStore('route-store', {
    state: (): RouteState => ({
        isInitAuthRoute: false,
        routeHomeName: PageNames.HOME,
        menus: [],
        searchMenus: [],
        cacheRoutes: [],
        clearCacheRoutes: []
    }),
    actions: {
        /** 初始化权限路由 */
        async initAuthRoute() {
            console.debug('初始化权限路由...')
            await this.initDynamicRoute()
        },
        /** 初始化动态路由 */
        async initDynamicRoute() {
            const { resetAuthStore } = useAuthStore()
            const { error, result } = await JBoltApi.get<ResData<Menu[]>>(
                '/api/user/permission/menus'
            )
            if (!error) {
                const menus = result.data ?? []
                //第一个加上home
                menus.unshift({
                    id: '0',
                    name: import.meta.env.VITE_ROUTE_HOME_TITLE,
                    isMenu: true,
                    permissionKey: PageNames.HOME,
                    url: import.meta.env.VITE_ROUTE_HOME_PATH,
                    icons: 'icon-park-outline:analysis',
                    openType: OpenType.DEFAULT
                })
                menus.push(...DemoMenus)
                this.handleMenu(menus)
                this.isInitAuthRoute = true
            } else {
                resetAuthStore()
            }
        },
        /**
         * 处理权限路由
         * @param menus - 权限路由
         */
        handleMenu(menus: Menu[]) {
            ;(this.menus as App.GlobalMenuOption[]) = transformMenu(menus)
            this.searchMenus = transformSearchMenus(menus)

            //todo 待处理
            // this.cacheRoutes = getCacheRoutes(vueRoutes)
        },
        /** 重置路由的store */
        resetRouteStore() {
            this.resetRoutes()
            this.$reset()
        },
        /** 重置路由数据，保留固定路由 */
        resetRoutes() {
            const routes = router.getRoutes()
            routes.forEach((route) => {
                const name = route.name || PageNames.ROOT
                if (!this.isConstantRoute(name)) {
                    router.removeRoute(name)
                }
            })
        },
        /**
         * 是否是固定路由
         * @param name 路由名称
         */
        isConstantRoute(name: RouteRecordName) {
            const constantRouteNames = getConstantRouteNames(constantRoutes)
            return constantRouteNames.includes(name)
        },

        /** 清除某个路由的当前缓存，一般在刷新和关闭页面时使用 */
        clearRouteCache(path: string) {
            this.clearCacheRoutes.push(path)
            setTimeout(() => {
                const index = this.clearCacheRoutes.findIndex((item) => item == path)
                if (index > -1) {
                    this.clearCacheRoutes.splice(index, 1)
                }
            }, 1000)
        },

        //todo 以下方法需要重写

        /** 从缓存路由中去除某个路由 */
        removeCacheRoute(name: AuthRoute.AllRouteKey) {
            const index = this.cacheRoutes.indexOf(name)
            if (index > -1) {
                this.cacheRoutes.splice(index, 1)
            }
        },

        /** 添加某个缓存路由 */
        addCacheRoute(name: AuthRoute.AllRouteKey) {
            const index = this.cacheRoutes.indexOf(name)
            if (index === -1) {
                this.cacheRoutes.push(name)
            }
        }
    }
})
